package com.bk.cyxf;

import jt.classic.system.ISystem;
import jt.classic.system.database.SystemDataSource;
import jt.classic.system.log.LogManager;
import jt.classic.system.user.IUser;
import jt.classic.system.user.UserManager;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import org.limp.mine.DataTrimmerI;
import org.limp.mine.DataTrimmerI.DataItemList;
import org.limp.mine.StringTool;

import java.sql.Connection;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class SSOLoginAction extends Action {
    public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        ActionForward forward = null;

        String logid = StringTool.checkString(request.getParameter("logid"),
                "-1");

        String pwd = StringTool.checkString(request.getParameter("pwd"), "-1");

        String url = StringTool.checkString(request.getParameter("url"), "-1");

        IUser user = null;

        Connection conn = null;

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            String sql = "SELECT ID FROM ISYS_USER WHERE LOGID = ? AND PASSWORD1 = ?";

            DataTrimmerI trimmer = new DataTrimmerI(conn);

            DataItemList dil = trimmer.createDIL();
            dil.set(logid);
            dil.set(pwd);

            Map info = trimmer.searchSingleData(sql, dil);

            if (info != null) {
                String userId = (String) info.get("ID");

                UserManager manager = new UserManager();
                user = manager.getUserById(userId);

                LogManager lm = new LogManager(conn);

                lm.log(user, request.getRemoteAddr(), request.getRemoteAddr(), "", "remotelogin",
                    "insert", user.iname() + " log-in");

                conn.commit();
                ISystem.createSessionUser(request, user);
                response.sendRedirect(url);
            }
        } catch (Exception ex) {
            try {
                conn.rollback();
            } catch (Exception ex1) {
                ISystem.catchException(request, this, ex);
            }

            ISystem.catchException(request, this, ex);

            request.setAttribute("result", ex.getMessage());
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        if (user == null) {
            request.setAttribute("result", "无效的用户名或密码");
        } else if (user.iflag() < 0) {
            request.setAttribute("result", "用户帐号已冻结");
        }

        return mapping.findForward("result");
    }
}
